package com.example.user.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.example.user.service.PhoneMsgService;
import com.example.user.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: gxcwhd
 * @BelongsPackage: com.example.user.service.impl
 * @Author: huan
 * @CreateTime: 2020-08-13 17:43
 * @Description:
 */
@Service
public class PhoneMsgServiceImpl implements PhoneMsgService {

    @Autowired
    private RedisService redisService;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Override
    public String sendPhoneMsg(String phoneNum) {

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FyFWayMx2qKrpYJHJd7", "VZnociNSDZRHPq0Mu44r44bSOzh25e");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("SignName", "ABCDE商城");
        request.putQueryParameter("TemplateCode", "SMS_198672684");

        String randomCode = (new Random().nextInt(899999) + 100000) + "";

//        redisService.setExpire(phoneNum,randomCode,1000 * 60 * 5);

        redisTemplate.opsForValue().set(phoneNum,randomCode,300, TimeUnit.SECONDS);// 表示xx秒过期

        request.putQueryParameter("TemplateParam", "{\"code\":\""+ randomCode +"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return "发送成功";
    }
}
